package com.xuerhua.yxt.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xuerhua.yxt.dao.TeacherMonthPointsMapper;
import com.xuerhua.yxt.dao.TeacherTermPointsMapper;
import com.xuerhua.yxt.model.TeacherMonthPoints;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.PointsReqVO;
import com.xuerhua.yxt.service.ITeacherPointService;
import com.xuerhua.yxt.view.PointItemView;
import com.xuerhua.yxt.view.PointTotalView;

@Service("teacherPointService")
public class TeacherPointServiceImpl implements ITeacherPointService {

	@Autowired
	private TeacherTermPointsMapper teacherTermPointsMapper;
	@Autowired
	private TeacherMonthPointsMapper teacherMonthPointsMapper;
	
	@Override
	public int addTeacherMonthPoints(PointsReqVO vo) {
		return teacherMonthPointsMapper.addTeacherMonthPoints(vo);
	}

	@Override
	public int addTeacherTermPoints(PointsReqVO vo) {
		return teacherTermPointsMapper.addTeacherTermPoints(vo);
	}

	@Override
	public int updateTeacherTermPoints(PointsReqVO vo) {
		return teacherTermPointsMapper.updateTeacherTermPoints(vo);
	}

	@Override
	public int updateTeacherTotalPoints(PointsReqVO vo) {
		return teacherTermPointsMapper.updateTeacherTotalPoints(vo);
	}

	@Override
	public int updateTeacherMonthPoints(Integer teacherId, Float point) {
		int result = startUpdatePoints(teacherId, point);
		if(result == 0) {
			for(int i = 0; i < 2; i++) {
				result = startUpdatePoints(teacherId, point);
				if(result == 1) {
					break;
				}
			}
		}
		return result;
	}

	private int startUpdatePoints(Integer teacherId, Float point) {
		PointsReqVO vo = new PointsReqVO();
		vo.setKeyId(teacherId);
		TeacherMonthPoints teacher = teacherMonthPointsMapper.selectTeacherForCurrMonth(vo);
		Float points = teacher.getPoints() == null ? 0 : teacher.getPoints();
		teacher.setPoints(points + point);
		return teacherMonthPointsMapper.updateForVersionById(teacher);
	}

	@Override
	public PointTotalView selectTotalPointForTeacher(PointsReqVO vo) {
		return teacherTermPointsMapper.selectTotalPointForTeacher(vo);
	}

	@Override
	public List<PointTotalView> selectTotalPointForTeacherByPage(Page<PointTotalView> page) {
		return teacherTermPointsMapper.selectTotalPointForTeacherByPage(page);
	}

	@Override
	public List<PointItemView> selectPointItemForTeacherByPage(Page<PointItemView> page) {
		return teacherTermPointsMapper.selectPointItemForTeacherByPage(page);
	}

}
